package com.localjoycommunity.cpdj.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.vod.model.v20170321.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: lida
 * @Date: 2020/7/29 0029 上午 11:46
 * @Description: 视频点播
 */
public class VodUtil {

    /**
     * 搜索媒资信息
     * @param client 发送请求客户端
     * @return SearchMediaResponse 搜索媒资信息响应数据
     * @throws Exception
     */
    public static SearchMediaResponse searchMedia(DefaultAcsClient client,Integer pageNo,Integer pageSize) throws Exception {
        SearchMediaRequest request = new SearchMediaRequest();
        request.setFields("Title,CoverURL,Status");
        request.setMatch("Status in ('Normal','Checking')");
        request.setPageNo(pageNo);
        request.setPageSize(pageSize);
        request.setSearchType("video,audio");
        request.setSortBy("CreationTime:Desc");
        return client.getAcsResponse(request);
    }

    /**
     * 批量获取视频信息
     * @param videoIds
     * @return
     * @throws Exception
     */
    public static List<Map<String,String>> getVideoInfos(String videoIds) throws Exception {
        List<Map<String,String>> list = new ArrayList<>();
        Map<String,String> detail = new HashMap<>();
        Map<String,String> sts = getTokenBySTS();
        DefaultAcsClient client = initVodClient(sts.get("accessKeyId"),sts.get("accessKeySecret"),sts.get("securityToken"));
        GetVideoInfosResponse  response = getVideoInfos(client,videoIds);
        for (GetVideoInfosResponse.Video video : response.getVideoList()) {
            detail.put("desc",video.getDescription());
            detail.put("title",video.getTitle());
            detail.put("cover ",video.getCoverURL());
            detail.put("status ",video.getStatus());
            list.add(detail);
        }
        return list;
    }

    /**
     * 获取播放地址
     * @param client
     * @param videoId
     * @return
     * @throws Exception
     */
    public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client,String videoId) throws Exception {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 获取播放凭证
     * @param client
     * @param videoId
     * @return
     * @throws Exception
     */
    public static GetVideoPlayAuthResponse getVideoPlayAuth(DefaultAcsClient client,String videoId) throws Exception {
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 获取视频信息
     * @param client 发送请求客户端
     * @param videoId 视频ID
     * @return GetVideoInfoResponse 获取视频信息响应数据
     * @throws Exception
     */
    public static GetVideoInfoResponse getVideoInfo(DefaultAcsClient client,String videoId) throws Exception {
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 批量获取视频信息函数
     * @param client 发送请求客户端
     * @param videoIds 视频ID
     * @return GetVideoInfosResponse 获取视频信息响应数据
     * @throws Exception
     */
    public static GetVideoInfosResponse getVideoInfos(DefaultAcsClient client,String videoIds) throws Exception {
        GetVideoInfosRequest request = new GetVideoInfosRequest();
        request.setVideoIds(videoIds);
        return client.getAcsResponse(request);
    }

    /**
     * 获取 securityToken，accessKeyId,  accessKeySecret
     * @return
     * @throws ClientException
     */
    public static Map<String,String> getTokenBySTS() throws ClientException {
        Map<String,String> result = new HashMap<>();
        String accessKeyId = "LTAI4GJwbUJatbN6N9XRidBK";
        String accessKeySecret = "KE1CUIAqax9d8xFMibcf7srJkQAvcv";
        String roleArn = "acs:ram::1394118542265292:role/vod";
        String roleSessionName = "session-vod";
        String policy = "{\n" +
                "  \"Version\": \"1\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Action\": \"vod:*\",\n" +
                "      \"Resource\": \"*\",\n" +
                "      \"Effect\": \"Allow\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy);
        result.put("securityToken",response.getCredentials().getSecurityToken());
        result.put("accessKeyId",response.getCredentials().getAccessKeyId());
        result.put("accessKeySecret",response.getCredentials().getAccessKeySecret());
        return result;
    }

    /**
     * 获取子用户权限
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param roleArn
     * @param roleSessionName
     * @param policy
     * @return
     * @throws ClientException
     */
    private static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy) throws ClientException {
        //构造default profile（参数留空，无需添加Region ID）
            /*
            说明：当设置SysEndpoint为sts.aliyuncs.com时，regionId可填可不填；反之，regionId必填，根据使用的服务区域填写，例如：cn-shanghai
            详情参考STS各地域的Endpoint，请参见接入地址（https://help.aliyun.com/document_detail/66053.html?spm=a2c4g.11186623.2.16.1db87074dzvl3J#reference-sdg-3pv-xdb）。
             */
        IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
        //用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setEndpoint("sts.aliyuncs.com");
        request.setMethod(MethodType.POST);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        // 发起请求，并得到response
        final AssumeRoleResponse response = client.getAcsResponse(request);
        return response;
    }

    /**
     * 使用STS初始化Vod客户端
     * @param accessKeyId
     * @param accessKeySecret
     * @param securityToken
     * @return
     * @throws ClientException
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret, String securityToken) throws ClientException {
        // 点播服务接入区域
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret, securityToken);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

}
